<template>
  <layout>
    <div class="content">
      <el-form :model="form" label-width="auto" class="form">
        <el-form-item label="工 号">
          <el-input v-model="form.name" ref="nameRef" @keydown.enter="setPwdInputFocus" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="密 码">
          <el-input type="password" ref="passwordRef" placeholder="请输入密码" @keydown.enter="login(true)"
            v-model="form.password" />

        </el-form-item>
        <el-form-item>
          <div class="button-section">
            <el-button type="primary" @click="login(true)" :loading="logining">登 录</el-button>
            <el-button type="success" @click="exit()">关 闭</el-button>
            <el-button type="success" @click="index()">首 页</el-button>
            <el-button type="success" @click="test()">test</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </layout>
</template>
<script setup>
import { ipc, isEE } from "@/utils/ipcRenderer";
import { ref, onMounted, useTemplateRef, reactive, onUnmounted, provide } from "vue";
import { useUserStore } from "@/store/userStore";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ipcApiRoute } from "@/api";
import layout from "./layout.vue";
import { setToken } from '@/utils/auth'

const nameRef = useTemplateRef('nameRef')
const namepasswordRefRef = useTemplateRef('passwordRef')

const userStore = useUserStore()
const logining = ref(false)

const form = reactive({
  name: '',
  password: ''
})

// Provide the form data for child components to inject
provide('loginForm', form)

const router = useRouter()

//验证输入
function validate() {
  if (!form.name) {
    ElMessage.error("请输入工号");
    return false
  }
  if (!form.password) {
    ElMessage.error("请输入密码");
    return false
  }
  return true;
}

//退出应用
function exit() {
  ipc.send(ipcApiRoute.exitApp);
}

function login(isOpenMain = false) {
  if (!validate())
    return;
  logining.value = true;


  userStore.login(form.name, form.password).then(res => {
    logining.value = false;
    if (!res.success) {
      console.log(res);
      if (res.regUrl) {
        ipc.invoke(ipcApiRoute.createWindow, {
          windowName: 'window-web',
          windowTitle: 'fdapply',
          contentUrl: res.regUrl,
        })

      } else {
        ElMessage.error(res.message);
      }
      return;
    }
    ipc.invoke(ipcApiRoute.openMain, {}).then(res => {
      if (res.success) {
        router.push({ name: "Home", params: { url: res.url } })
      }
    })
    // router.push({ path: "/lock" })

  });
}

function index() {
  router.push({ path: "/home" });
  ipc.send(ipcApiRoute.openHome, {});
}
function test() {
  debugger;
  // ipc.invoke(ipcApiRoute.test, {}).then(res => {
  //   debugger;
  //   console.log(res);
  // })
  window.electron.test().then(res => {
    debugger;
    console.log(res);
  })
}

// 在 index.vue 的 script setup 部分添加
// function resizeWindow(width, height) {
//   window.electronAPI.resizeWindow(width, height);
// }


function setPwdInputFocus() {
  namepasswordRefRef.value.focus();
}
function close() {

}

const handleProtocolCall = () => {
  if (!isEE) {
    return;
  }
  ipc.on('protocol-call', (event, data) => {
    if (data.protocol == "login") {
      // 从协议参数获取凭证
      const { username, password } = data.params;

      // 更新表单并触发登录
      if (username) form.name = username;
      if (password) form.password = password;
      login(true);
    }
  });
};

const webLoginSuccess = () => {
  if (!isEE) {
    return;
  }
  ipc.on('web-login-success', (event, data) => {
    console.log('登录成功:', data);
    setToken(data.cookie);
    // ipc.invoke(ipcApiRoute.openMain, {})
    router.push({ path: "/lock" })
  });
};

const getUserName = () => {
  // 获取配置
  ipc.invoke(ipcApiRoute.getConfig, "userName").then(value => {
    if (value) {
      form.name = value;
      setPwdInputFocus();
    }
  });
}
onMounted(() => {
  nameRef.value.focus();

  handleProtocolCall();

  webLoginSuccess();

  ipc.send('page-ready'); // 通知主进程页面已就绪

  getUserName();
})

onUnmounted(() => {
  ipc.removeAllListeners('protocol-call');
  ipc.removeAllListeners('web-login-success');
});

</script>
<style scoped lang="less">
.content {
  padding: 0 10px;

  .form {
    margin: 0 auto;
    margin-top: 30px;
    padding: 0 150px;
    max-width: 600px;
    min-width: 300px;

    .button-section {
      width: 100%;
      text-align: center;

      &>button:last-child {
        margin-left: 50px;
      }
    }
  }

  flex: 1;
}
</style>